//
//  CartoonSaveViewController.m
//  A段项目,漫画
//
//  Created by dlios on 15-4-23.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "CartoonSaveViewController.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface CartoonSaveViewController ()
@property(nonatomic, retain)NSMutableArray *saveCartoonArr;
@property(nonatomic, retain)UICollectionView *saveCartoonCollection;
@property(nonatomic, retain)UIAlertView *deleteAlert;
@property(nonatomic, assign)BOOL isWobble;
//动画
@property(nonatomic, retain)UIView *witeView;
@property(nonatomic, retain)NSMutableArray *witeImageArr;
@property(nonatomic, retain)UIImageView *witeImageView;
@property(nonatomic, retain)UIProgressView *myProgress;
@property(nonatomic, retain)UILabel *myLabel;
@end

@implementation CartoonSaveViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.saveCartoonArr = [NSMutableArray array];
        [self loadSaveCartoon];
        self.isWobble = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor cyanColor];
    self.navigationItem.title = @"漫画收藏";
    [self createAvtivity];
    [self createWiteImage];
    [self creatView];
    [self createfootView];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"清空" style:UIBarButtonItemStylePlain target:self action:@selector(clear)];
    NSLog(@"COUNT   %ld",self.saveCartoonArr.count);
    [self.view bringSubviewToFront:self.witeView];
    //播放动画
    [self.witeImageView startAnimating];
}

- (void)createWiteImage{
    self.witeImageArr = [NSMutableArray array];
    NSArray *names = @[@"735d4677ec7cdd522281cfbddd29ac71－1（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－2（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－3（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－4（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－5（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－6（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－7（被拖移）.tiff", @"735d4677ec7cdd522281cfbddd29ac71－8（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－9（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－10（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－11（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－12（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－13（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－14（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－15（被拖移）.tiff",
                       @"735d4677ec7cdd522281cfbddd29ac71－16（被拖移）.tiff"];
    
    for (NSString *name in names) {
        UIImage *image = [UIImage imageNamed:name];
        [self.witeImageArr addObject:image];
    }
    self.witeImageView.animationImages = self.witeImageArr;
    //设置播放时间
    self.witeImageView.animationDuration = 0.5;
}
- (void)createAvtivity{
    self.witeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.witeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.witeView];
    [self.witeView release];
    CGFloat bili = 222.0 / 271;
    self.witeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 1.5, WIDTH / 1.5 * bili)];
    self.witeImageView.center = CGPointMake(WIDTH / 2, HEIGHT / 3);
    [self.witeView addSubview:self.witeImageView];
    [self.witeImageView release];
    
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 1.5, 30)];
    self.myLabel.center = CGPointMake(WIDTH / 2, HEIGHT / 3 + WIDTH / 1.5 * bili / 2 + 10);
    self.myLabel.text = @"loading..........";
    [self.witeView addSubview:self.myLabel];
    self.myLabel.textAlignment = NSTextAlignmentCenter;
    //    self.myProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(100, WIDTH - 50, 200, 30)];
    //    self.myProgress.center = CGPointMake(WIDTH / 2, HEIGHT / 2 - 10);
    //    [self.myProgress setProgressViewStyle:UIProgressViewStyleDefault];
}
#pragma mark 创建视图
-(void)creatView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    CGFloat bili = 107.0 / 80;
    flow.itemSize = CGSizeMake(WIDTH / 4, WIDTH / 4 * bili);
    flow.minimumInteritemSpacing = 20;
    flow.minimumLineSpacing = 40;
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.sectionInset = UIEdgeInsetsMake(20, 10, 20, 20);
    
    self.saveCartoonCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flow];
    [self.view addSubview:self.saveCartoonCollection];
    [self.saveCartoonCollection release];
    [self.saveCartoonCollection registerClass:[ClassifyDetailCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    self.saveCartoonCollection.delegate = self;
    self.saveCartoonCollection.dataSource = self;
    UIImage *image = [UIImage imageNamed:@"3ad3a4b5b42ccdb508dbd351bfa92a2b.jpeg"];
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    backImage.image = image;
    [self.saveCartoonCollection setBackgroundView:backImage];
    
    //给空白处添加点击
    UITapGestureRecognizer *backTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backTapAction:)];
    //打开交互
    self.saveCartoonCollection.backgroundView.userInteractionEnabled = YES;
    [self.saveCartoonCollection.backgroundView addGestureRecognizer:backTap];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)longPress{
    NSLog(@"长按");
    self.isWobble = YES;
    [self.saveCartoonCollection reloadData];
}

- (void)doubleTapAction:(UITapGestureRecognizer *)doubleTap{
    NSLog(@"双击");
}

- (void)backTapAction:(UITapGestureRecognizer *)tap{
    NSLog(@"%ld",tap.numberOfTouches);
    NSLog(@"点击");
    self.isWobble = NO;
    [self.saveCartoonCollection reloadData];
}

#pragma mark 清空按钮的点击方法
-(void)clear
{
    self.deleteAlert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"确定要清空收藏吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.deleteAlert show];
    [self.deleteAlert release];
}
#pragma mark 协议方法的实现
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.saveCartoonArr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ClassifyDetailCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    saveCartoon *save = self.saveCartoonArr[indexPath.row];
    NSURL *url = [NSURL URLWithString:save.picURL];
    //打开图片的交互
    cell.myImageView.userInteractionEnabled = YES;
    //创建手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
    //设置长按所需的最短时间
    longPress.minimumPressDuration = 1;
    [cell.myImageView addGestureRecognizer:longPress];
    [longPress release];
    
    [cell.myImageView sd_setImageWithURL:url];
    
    cell.myImageView.layer.borderWidth = 1.5;
    cell.myImageView.layer.cornerRadius = 10;
    cell.myImageView.layer.borderColor = [UIColor clearColor].CGColor;
    cell.myImageView.layer.masksToBounds = YES;
    cell.titleLabel.text = save.title;
    if (self.isWobble) {
        cell.deleteImage.image = [UIImage imageNamed:@"deleteTag.png"];
        [self BeginWobbleForCell:cell];
    }else{
        cell.deleteImage.image = nil;
        [self EndWobbleForCell:cell];
    }
    [self.witeImageView stopAnimating];
    [self.view bringSubviewToFront:self.saveCartoonCollection];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.isWobble) {
        CartoonDViewController *cartoonVC = [[CartoonDViewController alloc] init];
        saveCartoon *save = self.saveCartoonArr[indexPath.row];
        cartoonVC.comic_id = save.comic_id;
        [self.navigationController pushViewController:cartoonVC animated:YES];
    }else{
        NSLog(@"开始删除 ");
        //在晃动中,再次点击删除
        saveCartoon *save = self.saveCartoonArr[indexPath.row];
        //打开数据库
        [[DataBaseHandle shareDB] openDB];
        //打开表
        [[DataBaseHandle shareDB] createCartoonTable];
        //删除动漫数据
        [[DataBaseHandle shareDB] deleteCartoonWithID:save.comic_id];
        //关闭数据库
        [[DataBaseHandle shareDB] closeDB];
        //刷新数据
        [self.saveCartoonArr removeObjectAtIndex:indexPath.row];
        [self.saveCartoonCollection reloadData];
    }
}

- (void)loadSaveCartoon{
    //打开数据库
    [[DataBaseHandle shareDB] openDB];
    //创建表
    [[DataBaseHandle shareDB] createCartoonTable];
    //查询Id
    self.saveCartoonArr = [[DataBaseHandle shareDB] selectSaveCartoon];
    //关闭数据库
    [[DataBaseHandle shareDB] closeDB];
    
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //打开数据库
        [[DataBaseHandle shareDB] openDB];
        //打开表
        [[DataBaseHandle shareDB] createCartoonTable];
        //删除表
        [[DataBaseHandle shareDB] dropCartoonTable];
        //关闭数据库
        [[DataBaseHandle shareDB] closeDB];
        [self loadSaveCartoon];
        [self.saveCartoonCollection reloadData];
    }
}

- (void)createfootView
{
    [self.saveCartoonCollection addHeaderWithCallback:^{
        [self loadSaveCartoon];
        [self.saveCartoonCollection reloadData];
        [self.saveCartoonCollection headerEndRefreshing];
    }];
}

//图片抖动
-(void)BeginWobbleForCell:(UICollectionViewCell *)cell
{
    srand([[NSDate date] timeIntervalSince1970]);
    float rand=(float)random();
    CFTimeInterval t=rand*0.0000000000001;
    [UIView animateWithDuration:0.01 delay:t options:0  animations:^
     {
         cell.transform=CGAffineTransformMakeRotation(-0.05);
     } completion:^(BOOL finished)
     {
         [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction  animations:^
          {
              cell.transform=CGAffineTransformMakeRotation(0.05);
          } completion:^(BOOL finished) {}];
     }];
}

-(void)EndWobbleForCell:(UICollectionViewCell *)cell
{
    [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState animations:^
     {
         cell.transform=CGAffineTransformIdentity;
     } completion:^(BOOL finished) {}];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
